package org.example.filesfind;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//Find files by last modified time
public class FileFindExample3 {
    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) throws IOException {
        List<Path> result = findByLastModifiedTime(Paths.get("F:\\迅雷下载"),Instant.now().minus(1, ChronoUnit.DAYS));
        for (Path path : result) {
            BasicFileAttributes attrs = Files.readAttributes(path,BasicFileAttributes.class);
            FileTime time = attrs.lastModifiedTime();
            LocalDateTime localDateTime = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            System.err.println(String.format("%-40s [%s]",path,localDateTime.format(formatter)));
        }

    }

    static List<Path> findByLastModifiedTime(Path path, Instant instant){
        List<Path> result = null;
        try (Stream<Path> pathStream = Files.find(path, Integer.MAX_VALUE, new BiPredicate<Path, BasicFileAttributes>() {
            @Override
            public boolean test(Path path, BasicFileAttributes basicFileAttributes) {
                if (Files.isDirectory(path) || !Files.isReadable(path)) {
                    return false;
                }
                FileTime fileTime = basicFileAttributes.lastModifiedTime();
                int i = fileTime.toInstant().compareTo(instant);
                return i > 0;
            }
        })) {
            result = pathStream.collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
